package com.staticUtils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jinrong.wang
 */
public class HttpClientMethod {


    /**
     * 调用this方法
     * @return
     */
    public String query() throws IOException {
        String result = this.doPost("111", "222", new HashMap<String, String>());
        return result;
    }

    public String doPost(String url, String jsonParams, Map<String, String> headmap) throws IOException {
        String responseStr = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).setRedirectsEnabled(true).build();
        httpPost.setConfig(requestConfig);

        if (headmap != null && headmap.size() > 0) {
            for (String key : headmap.keySet()) {
                httpPost.setHeader(key, headmap.get(key));
            }
        }
        try {
            if (jsonParams != null && !"".equals(jsonParams)) {
                httpPost.setEntity(new StringEntity(jsonParams, "UTF-8"));
                CloseableHttpResponse response = httpClient.execute(httpPost);
                if (response != null && response.getStatusLine().getStatusCode() == 200) {
                    responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                    return responseStr;
                } else {
                    return "!200";
                }
            }
        } catch (Exception e) {
            System.out.println("异常");
//            e.printStackTrace();
            throw e;
        }

        return "222";
    }
}
